<template>
    <div class="about">
      <!-- 查询区----start -->
        <el-form  :inline="true" ref="formSearch" :model="formSearch" class="demo-form-inline">
            <el-form-item label="广告图片名称">
                <el-input v-model="formSearch.name" placeholder="请输入广告图片名称"></el-input>
            </el-form-item>
            <el-form-item label="图片位置">
                  <el-select v-model="formSearch.positionId" placeholder="图片位置">
                     <el-option
                        v-for="item in testData"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                      </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="状态">
                <el-select v-model="formSearch.status" placeholder="请选择">
                    <el-option label="全部" value="" ></el-option>
                    <el-option label="上线" value="1"></el-option>
                    <el-option label="下线" value="0"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="上线日期">
                <el-date-picker
                   v-model="formSearch.startTime"
                   type="date"
                   placeholder="选择上线日期时间"
                   align="right"
                   :picker-options="pickerOptions"
                >
                </el-date-picker>
            </el-form-item>
            <el-form-item label="下线日期">
                <el-date-picker
                   v-model="formSearch.endTime"
                   type="date"
                   placeholder="选择下线日期时间"
                   align="right"
                   :picker-options="pickerOptions"
                >
                </el-date-picker>
            </el-form-item>
            <el-form-item label="操作" style="margin-left:50px;">
                <el-button type="primary"  icon="el-icon-search" @click="loadData()">查询</el-button>
                <el-button type="warning" icon="el-icon-refresh-right plain" @click="formSearch={}">重置</el-button>
                <el-button type="primary" icon="el-icon-circle-plus"  @click="addbtn()">添加</el-button>
            </el-form-item>
        </el-form>
        <!-- 查询区----end -->
    <el-table
        :data="tableData"
        style="width: 100%">
        <el-table-column
            prop="name"
            label="广告图片名称"
            width="180">
        </el-table-column>
        <el-table-column
            prop="pic"
            label="广告图片"
            width="200px">
            <template slot-scope="scope">
              <el-popover trigger="hover" placement="top">
                <div style="padding-left:18%;width:300px">
                <p>图片：</p><img  :src="scope.row.pic"  style="width: 200px;height: 200px">
                <p>图片跳转地址:</p><a :href="scope.row.url"><span v-html="scope.row.url"></span></a>
                </div>
              <div slot="reference" class="name-wrapper">
                  <img  :src="scope.row.pic"  style="width: 100px;height: 100px">
              </div>
              </el-popover>
            </template>
        </el-table-column>
        <el-table-column 
            prop="positionId"
            label="图片位置"
            width="180">
            <template slot-scope="scope" >
              <div v-for="item in testData" :key="item.id">
                <div v-if="item.id==scope.row.positionId">
                  {{ item.name}}
                </div>
              </div>
             </template>
        </el-table-column>
        <el-table-column
            prop="clickCount"
            label="点击量"
            sortable>
        </el-table-column>
         <el-table-column
            prop="orderCount"
            label="下单数"
            sortable>
        </el-table-column>
          <el-table-column
            prop="status"
            label="状态"
            sortable>
            <template slot-scope="scope">
              <span>{{scope.row.status | status() }}</span>
            </template>
        </el-table-column>
        <el-table-column
            label="上线日期"
            width="180">
      <template slot-scope="scope">
        <i class="el-icon-time"></i>
        <span style="margin-left: 10px">{{ scope.row.startTime | dateFilter("yyyy-mm-dd hh:mm:ss")  }}</span>
      </template>
    </el-table-column>
    <el-table-column
      label="下线日期"
      width="180">
      <template slot-scope="scope">
        <i class="el-icon-time"></i>
        <span style="margin-left: 10px">{{ scope.row.endTime | dateFilter("yyyy-mm-dd hh:mm:ss") }}</span>
      </template>
    </el-table-column>
    <el-table-column
        prop="note"
        label="备注">
    </el-table-column>
     <el-table-column label="操作" width="250px" fixed="right">
      <template slot-scope="scope">
        <el-button
          size="mini"
          @click="offline(scope.row)">{{ scope.row.status | statusbtn() }}</el-button>
          <el-button
          size="mini"
          type="success"
          @click="handleEdit(scope.row)">编辑</el-button> 
        <el-button
          size="mini"
          type="danger"
          @click="handleDelete(scope.row)">删除</el-button>
      </template>
    </el-table-column>
    </el-table>
     <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[2,3,5,10,100, 200, 300, 400]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>

     <!--添加弹出框-->
            <el-dialog :title="title" :visible.sync="addFormVisible">
                <el-form :model="form" :inline="true" label-width="200px">
                    <el-form-item label="广告图片名称" >
                        <el-input v-model="form.name" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="图片链接地址" >
                        <el-input v-model="form.url" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="图片位置">
                       <el-select v-model="form.positionId" placeholder="请选择图片位置">
                          <el-option
                                  v-for="item in testData"
                                  :key="item.id"
                                  :label="item.name"
                                  :value="item.id">
                          </el-option>
                        </el-select>
                    </el-form-item>
                     <el-form-item label="备注" >
                        <el-input v-model="form.note" autocomplete="off"></el-input>
                    </el-form-item>

                     <el-form-item label="上线日期">
                <el-date-picker
                   v-model="form.startTime"
                   type="date"
                   placeholder="选择上线日期时间"
                   align="right"
                   :picker-options="pickerOptions"
                >
                </el-date-picker>
            </el-form-item>
            <el-form-item label="下线日期">
                <el-date-picker
                   v-model="form.endTime"
                   type="date"
                   placeholder="选择下线日期时间"
                   align="right"
                   :picker-options="pickerOptions"
                >
                </el-date-picker>
            </el-form-item>

                    <el-form-item label="轮播图上传">
                        <!--图片上传-->
                        <el-upload
                                class="avatar-uploader"
                                :action="url"
                                name="file"
                                :auto-upload='true'
                                :show-file-list="false"
                                :on-success="handleAvatarSuccess"
                                :before-upload="beforeAvatarUpload">
                            <img v-if="imageUrl" :src="imageUrl" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="addFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="add()">确 定</el-button>
                </div>
              </el-dialog>
    </div>
</template>
 <script>
    export default {
      data() {
        return {
          url:this.$base_url+"/api/cs/commonOSS/upload?accessToken="+localStorage.getItem("token"),
          tableData: [],
          currentPage:1,//当前页面，默认1
                pageSize:5,//每页显示条数
                total:100,//分页总数量，默认值随便写，初始化时赋予新值
                name:'',//查询功能
                addFormVisible:false,
                title:'',
                imageUrl:'',
                form:{},
                testData: [],
                picName:'',
                seen:false,
                formSearch: {},
                pickerOptions: {
                shortcuts: [{
                  text: '今天',
                  onClick(picker) {
                    picker.$emit('pick', new Date());
                  }
                }, {
                  text: '昨天',
                  onClick(picker) {
                    const date = new Date();
                    date.setTime(date.getTime() - 3600 * 1000 * 24);
                   picker.$emit('pick', date);
                  }
                }, {
                  text: '一周前',
                  onClick(picker) {
                    const date = new Date();
                    date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                    picker.$emit('pick', date);
                  }
          }]
        },
        }
      }, 
      created:function(){
        this.loadData();
        this.testSite();
            },
    methods: {
        loadData(){
          this.$http.post("/api/mks/advertise/queryAll?pageNo="+this.currentPage+"&pageSize="+this.pageSize,
          { name:this.formSearch.name,startTime:this.formSearch.startTime,endTime:this.formSearch.endTime,
          status:this.formSearch.status,positionId:this.formSearch.positionId }).then((response) => {
             if(response.data.code==2000){
              // alert(this.formSearch.startTime)
              //  console.log(response.data)
                this.tableData = response.data.data.list;
                this.total = response.data.data.total;
              } 
        })        
    },
    testSite(){
        this.$http.post("/api/mks/advertisePosition/query").then((response) => {
          // console.log(response.data)
            if(response.data.code==2000){
              this.testData=response.data.data;
              // console.log(this.testData)
            } 
        })
    },
     handleSizeChange(val) {
                    // console.log(`每页 ${val} 条`);
                    this.pageSize=val;
                    this.loadData();
       },
     handleCurrentChange(val) {
              // console.log(`当前页: ${val}`);
              this.currentPage=val;
              this.loadData();
      },search(){
        this.loadData();
      },addbtn(){
        this.form={};
        this.seen=true;
         this.title="添加";
         this.imageUrl="",
        this.addFormVisible=true;
      },handleEdit(row){
        var _row=row
        if(row.status==1){
          _row.status=-1
        }else if(row.status==0){
          _row.status=-2
        }
         this.form =  JSON.parse(JSON.stringify(_row))
        //this.form=_row;
        console.log(_row)
        this.imageUrl=_row.pic
        this.seen=false;
        this.title="修改";
        this.addFormVisible=true;
      },
       handleAvatarSuccess:function(res, file) {
                     //图片回显
                     this.imageUrl = URL.createObjectURL(file.raw);
                  //   alert(file.response);
                    // alert(JSON.stringify(file.response));
                     this.form.pic=file.response.ossFileUrlBoot;
                     // this.form.fileName=file.response.oldFileName;
                     // this.form.filePath=file.response.newFilePath;
                 },
                 //上传前图片类型和大小判断
                 beforeAvatarUpload:function(file) {
                     // const isJPG = file.type === 'image/jpeg';
                     const isLt5M = file.size / 1024 / 1024 < 5;

                     /* if (!isJPG) {
                          this.$message.error('上传头像图片只能是 JPG 格式!');
                      }*/
                     if (!isLt5M) {
                         this.$message.error('上传头像图片大小不能超过 5MB!');
                     }
                     return  isLt5M;
                 },
                 add:function(){
                   var _this =this;
                   if(this.seen){
                      this.$http.post("/api/mks/advertise/insert",this.form).then((response) => {
                        alert(JSON.stringify(this.form))
                          // console.log(response);
                      if(response.data.code==2000){
                          //提示成功
                          _this.$message({
                              type: 'success',
                              message: '添加成功!'
                          });
                          //关闭弹框
                          _this.addFormVisible=false;
                          //重新加载数据
                          _this.loadData();
                      }
                    }).catch(function (error) {
                              console.log(error);
                              this.$message.error("你错了。。。") 
                    })
                  }else{
                    // this.form.status='';
                    console.log(this.form)
                     this.$http.put('api/mks/advertise/update',this.form).then(function (response) {
                            // console.log(response);
                            if(response.status == 200&&response.data.code==2000){
                                    //提示成功
                                   _this.$message({
                                        type: 'success',
                                        message:'修改成功!'
                                    });
                                    _this.loadData();
                                    }}
                        ).catch(function (error) {
                             console.log(error);
                            _this.$message.error("你错了。。。") 
                     })
                     this.addFormVisible=false;
                   } 
                 },
                 //删除
                 handleDelete(row){
                   this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                     confirmButtonText: '确定',
                     cancelButtonText: '取消',
                     type: 'warning'
                         }).then(() => {
                            //  console.log(row.id)
                             var _this=this;
                          this.$http.delete('api/mks/advertise/deleteById?id='+row.id).then(function (response) {
                            console.log(response);
                            
                            if(response.status == 200&&response.data.code==2000){
                                    //提示成功
                                   _this.$message({
                                        type: 'success',
                                        message: '删除成功!'
                                    });
                                    _this.currentPage=1;
                                    _this.loadData();
                                    }}
                        ).catch(function (error) {
                            console.log(error);
                            this.$message.error("你错了。。。") 
          })   
                        }).catch(() => {
                            this.$message({
                             type: 'info',
                             message: '已取消删除'
                         });          
                     });
                 },offline(row){
                   var _row=row;
                   var title;
                    // console.log(_row);
                   if(row.status==1){
                     _row.status=0;
                     title="下线"
                   }else if(row.status==0){
                     _row.status=1;
                      title="上线"
                   }
                   var _this=this
                    this.$http.put('api/mks/advertise/update',_row).then(function (response) {
                            console.log(response);
                            if(response.status == 200&&response.data.code==2000){
                                    //提示成功
                                   _this.$message({
                                        type: 'success',
                                        message: title+'成功!'
                                    });
                                    this.currentPage=1;
                                    _this.loadData();
                                    }}
                        ).catch(function (error) {
                            // console.log(error);
                            this.$message.error("你错了。。。") 
          })
                 }
  },filters: {
        //时间格式处理
            dateFilter: function (data, format = "") {
                var dt = new Date(data);
                var y = dt.getFullYear();
                var m = (dt.getMonth()+1).toString().padStart(2,"0");
                var d = dt.getDate().toString().padStart(2,"0");
                var h = dt.getHours().toString().padStart(2,"0");
                var mm = dt.getMinutes().toString().padStart(2,"0");
                var s = dt.getSeconds().toString().padStart(2,"0");
                if (format.toLocaleLowerCase() === "yyyy-mm-dd" ||
                    format.toLocaleLowerCase() === "") {
                    return `${y}-${m}-${d}`;
                } else if (format.toLocaleLowerCase() === "yyyy/mm/dd") {
                    return `${y}/${m}/${d}`;
                } else if (format.toLocaleLowerCase() === "yyyy-mm-dd hh:mm:ss") {
                    return `${y}-${m}-${d} ${h}:${mm}:${s}`;
                } else if (format.toLocaleLowerCase() === "yyyy/mm/dd hh:mm:ss") {
                    return `${y}/${m}/${d} ${h}:${mm}:${s}`;
                } else {
                    return `输入的时间格式有误`;
                }
            },
          status: function(status){
            if(status==1){
              return '上线'
            }else{
              return '下线'
            }
          },statusbtn: function(status){
            if(status==0){
              return '上线'
            }else{
              return '下线'
            }
          }
        }
}
  </script>
  <style >
  .avatar-uploader .el-upload {
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
        }
        .avatar-uploader .el-upload:hover {
            border-color: #409EFF;
        }
        .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 100px;
            height: 100px;
            line-height: 100px;
            text-align: center;
        }
        .avatar {
            width: 100px;
            height: 100px;
            display: block;
        }
  </style>